﻿
namespace HSS.Xaml.UI.Controls
{
	#region Using Directives
	using System;
	#endregion

	#region DoubleClickDetection
	/// <summary>
	/// DoubleClickDetection for capturing Double Clicks of a control
	/// </summary>
	public class DoubleClickDetection
	{
		#region Fields
		private object previousSender;
		private DateTime previousClickTime;
		private TimeSpan timeDifference;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructor
		/// </summary>
		public DoubleClickDetection()
		{
			previousClickTime = DateTime.Now;
			timeDifference = System.TimeSpan.Zero;
		}
		#endregion

		#region Methods
		/// <summary>
		/// Processes a click event, and if less than 300 ms have elapsed since the same object was
		/// previously clicked, then assumes the user double clicked.
		/// </summary>
		/// <param name="sender">The object that was clicked.</param>
		/// <returns>true if the objects was double clicked; otherwise false.</returns>
		public bool ProcessClick(object sender)
		{
			var currentClickTime = DateTime.Now;
			if ((!object.ReferenceEquals(sender, this.previousSender)))
			{
				this.previousSender = sender;
				this.previousClickTime = currentClickTime;
				return false;
			}
			else
			{
				this.timeDifference = currentClickTime - this.previousClickTime;
				this.previousClickTime = currentClickTime;
				if (this.timeDifference.TotalMilliseconds <= 300)
				{
					this.previousSender = null;
					return true;
				}
				return false;
			}
		}
		#endregion
	}
	#endregion
}